package com.miracle.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miracle.entity.Menu;
import com.miracle.mapper.MenuMapper;
import com.miracle.service.MenuService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jie.xi
 * @date 2022年05月20日 10:54
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {


    @Override
    public List<Menu> getAllMenuList(String roleName) {
        //查出来所有的角色对应拥有的菜单
        List<Menu> allMenuList = this.baseMapper.getAllMenuList(roleName);
        //对菜单进行处理，返回前端需要的菜单格式
        List<Menu> menuList = new ArrayList<>();
        for(Menu menu:allMenuList){
            if(menu.getParentId() == null || menu.getParentId() == 0){
                //找到顶级菜单 在根据顶级菜单去找子菜单
                System.out.println(menu);
                findChildRen(menu,allMenuList);
                menuList.add(menu);
            }
        }
        return menuList;
    }

    private void findChildRen(Menu menu, List<Menu> menuList) {
        for (Menu child:menuList){
            if(child.getParentId() == menu.getId()){
                menu.getChildren().add(child);
            }
        }
        //如果是遍历完了之后，没有子菜单了说明找完了
        if(menu.getChildren()==null || menu.getChildren().size()==0){
            return;
        }
        for (Menu menu1:menu.getChildren()){
            findChildRen(menu1,menuList);
        }
    }
}
